package com.acme.bankapp.email;

public class EmailService {

    public EmailService() {
	thread.start();
    }

    public void sendNotificationEmail(final Email email)
	    throws QueueClosedException {
	queue.push(email);
    }

    public void close() {
	queue.close();
	try {
	    thread.join();
	} catch (InterruptedException e) {
	    e.printStackTrace();
	}
    }

    private void sendEmail(final Email email) {
	// simulate some time consuming activity
	try {
	    Thread.sleep(1000);
	} catch (InterruptedException e) {
	    e.printStackTrace();
	}
	System.out.println("email message has been sent to "
		+ email.getClient().getClientSalutation() + " ("
		+ email.getEmailAddress() + ")");
    }

    private Queue queue = new Queue();

    private Thread thread = new Thread(new Runnable() {
	public void run() {
	    try {
		while (!queue.isClosed() || !queue.isEmpty()) {
		    sendEmail(queue.pop());
		}
	    } catch (QueueClosedAndEmptyException e) {
		// we simply exit from queue.pop() when thread waits, queue is
		// empty and we close queue
	    }
	}
    });
}
